// 下滑刷新功能封装
import { reactive, onActivated, onDeactivated } from "vue"
import { onBeforeRouteUpdate, onBeforeRouteLeave } from "vue-router"
import $router from '@/router'
import { formatNumber } from "vant/lib/utils"
import { mobileResultCode } from '@/assets/js/common.js'
import $store from '@/store'
export const usePullRefresh = function  () {
	let request =  function() {}
	// 下拉刷新初始化
	const initPullRefresh = (config) => {
  //  定义请求地址
	if(config.request && typeof config.request === 'function') 
		request = config.request

	if(config.params)
		state.params = config.params
	}	
  const load = function (callback) {
		request({pageNo: ++state.pageNo, pageSize: state.pageSize, ...state.params, name: state.searchKey}).then(response => {
      const code = response.body.code 
			if(code === mobileResultCode.SUCCESS) {
				if(typeof callback === 'function' ) {
					callback()
				}
				state.items.push(...response.body.data.item)
				state.loading = false
				// 部分接口不返回totals所以是undefined
				state.total = response.body.data.totals
				if (state.total <= state.items.length) {	
      		state.finished = true
    		}
				if(state.refreshing) {
					state.refreshing = false
				}
			}else {
				forceFinish()
			}
		}).catch(error => {
			forceFinish()
		})
  }
	const forceFinish = () => {
		state.loading = false
		state.error = true
		state.refreshing = false
	}
  const state = reactive({
    items: [],
		// 加载数据中
    loading: false,
		// 刷新中
		refreshing: false,
		// 加载完成
    finished: false,
		// 加载过程中产生错误
    error: false,
		// 是否是刷新操作
    isreFreshLoading: false,
    pageNo: 0,
		pageSize: 10,
		params: {},
    total: 0,
		searchKey: '',
  })
  
	// 下拉刷新
  const onRefresh =  function () {
		let beanId
		if(state.params.beanId) {
			beanId = state.params.beanId
		}
		state.params = {beanId}
    // state.error = false
		reload()
  }

	// 重新加载数据
	const reload = function() {
		state.pageNo = 0
		load(() => {
			state.items = []
			state.finished = false
			state.isreFreshLoading = false
		})
	}

	// 搜索数据
	const onSearch = function(filterObj) {
		for (let k in filterObj) {
			state.params[k] = filterObj[k]
		}
		reload()
	}
	/**
	 * 缓存滚动位置：
	 *  1 detail返回列表页，才还原上一次滚动位置，否则不进行缓存，直接刷新列表
	 * 	2 缓存是通过vuex对父元素的offsetTop进行存储，组件激活时判断还原
	 * 	3 判断是否缓存是通过路由中的backactive属性进行判断，backactive是判断从该路由跳转至列表
	 * 			时是否需要缓存
	 * 	4 缓存与否需要动态修改路由组件的keepAlived属性，在路由进入前onBeforeRouterEnter时通过
	 * 			上一个路由的backactive来调整列表路由的keepAlived属性
	 */
	onActivated(() => {
		if( $store.getters.listScroll > 0 ) {
			document.getElementsByTagName('html')[0].scrollTop = $store.getters.listScroll
		}
	})

	onDeactivated(() => {
	})

	onBeforeRouteLeave(() => {
		const listScrollCache = document.getElementsByTagName('html')[0].scrollTop
		$store.dispatch('recordListScroll', listScrollCache)
	})

	onBeforeRouteUpdate(() => {
	})

  return {
    state,
    load,
    onRefresh,
		onSearch,
    $router,
		initPullRefresh
  }
}

// 前置守卫 根据上一个路由是否需要缓存动态修改跳转路由是否需要缓存
export const beforeRouteEnter = (to, from, next) => {
	!!!from.meta.cache & (to.meta.keepAlived = false)
	next()
}